package com.example.frameboot.common;

import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @Author zhangpan@centaline.com.cn
 * @Date 2020/6/28 17:37
 */
public class PageUtils {
    /**
     * 将PageInfo对象泛型中的Po对象转化为Vo对象
     *
     * @param <P>        Po类型
     * @param <V>        Vo类型
     * @param pageInfoPo PageInfo<Po>对象</>
     * @return
     */
    public static <P, V> PageInfo<V> PageInfo2PageInfoVo(PageInfo<P> pageInfoPo, List<V> v) {
        // 创建Page对象，实际上是一个ArrayList类型的集合
        PageInfo<V> page = new PageInfo<>(v);
        page.setTotal(pageInfoPo.getTotal());
        page.setPageSize(pageInfoPo.getPageSize());
        page.setPageNum(pageInfoPo.getPageNum());
        return page;
    }

    public static <T extends List> T startPage(T list, Integer pageNum,
                                               Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        T pageList = (T) list.subList(fromIndex, toIndex);

        return pageList;
    }
}
